import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Row, Col } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import CompClieZhsrMbsdCxForm from './CompClieZhsrMbsdCxForm'
import * as accountService from '../../../services/AccountDivi';
const daoName = "VCompClieKhglZx";
const ButtonGroup = Button.Group;
const columns = [
    { title: '客户名称', width: 215, sorter: true, dataIndex: 'CUNM', key: 'CUNM', dispaly: true, filter: true },
    { title: '组织机构代码', width: 140, sorter: true, dataIndex: 'ENCD', key: 'ENCD', dispaly: true, filter: true },
];
const controls = [
    { name: 'CUNM', required: true, type: 'text', label: '客户名称',  grid: 12 / 24 },
    { name: 'ENCD', required: true, type: 'text', label: '组织机构代码', min: 1, max: 50, grid: 12 / 24 },
];
const columnsUphmDivi = [
    { title: '开始日期', width: 120, sorter: true, key: 'SDATE', caption: "SDATE", render: data => datetime.format(data.SDATE, "yyyy-MM-dd"), dispaly: true, filter: true },
    { title: '结束日期', width: 120, sorter: true, key: 'EDATE', caption: "EDATE", render: data => datetime.format(data.EDATE, "yyyy-MM-dd"), dispaly: true, filter: true },
    { title: '目标上浮水平', width: 140, sorter: true, dataIndex: 'CKSD', key: 'CKSD', dispaly: true, filter: true },
    { title: '目标综合利润', width: 140, sorter: true, dataIndex: 'CKRJ', key: 'CKRJ', dispaly: true, filter: true },
    // { title: '利润(万元)', width: 130, sorter: true, dataIndex: 'MNLR', key: 'MNLR', dispaly: true, filter: true },
    // { title: '中收(万元)', width: 130, sorter: true, dataIndex: 'ZSSR', key: 'ZSSR', dispaly: true, filter: true },
];
const controlsUphm = [
    { name: 'SDATE', required: true, type: 'date', dataType:'date', label: '开始日期',  grid: 12 / 24 },
    { name: 'EDATE', required: true, type: 'date', dataType:'date', label: '结束日期', grid: 12 / 24 },
    { name: 'CKSD', required: true, type: 'number', dataType:'number', label: '目标上浮水平',  grid: 12 / 24 },
    { name: 'CKRJ', required: true, type: 'number', dataType:'number', label: '目标综合利润', grid: 12 / 24 },
    { name: 'MNLR', required: true, type: 'number', dataType:'number', label: '利润(万元)',  grid: 12 / 24 },
    { name: 'ZSSR', required: true, type: 'number', dataType:'number', label: '中收(万元)', grid: 12 / 24 },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class CompClieZhsrMbsdForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            diviList: [],
            glhmDataSource: [],
            diviDisplay: {
                div2: 'block',
                div3: 'none',
                lable1: '设置综合收益目标',
                isTj: true,
            },
            otherkey:-1
        };
    }
    componentWillReceiveProps(nextProps) {
        const k = nextProps.otherSelectedRowKeys.length
        if (k > 0) {
          this.state.otherkey = nextProps.otherSelectedRowKeys[k - 1]
        }
    };
    onSelectChangeHandler(newList, delKeys) {
      let diviList = this.state.diviList
      newList.map(data => {
        diviList.push(data)
      })
      delKeys.map(key => {
        const index = diviList.findIndex(divi => divi["CUID"] === key)
        diviList.splice(index, 1)
      })
      this.setState({ diviList })
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "CUID", permID: this.props.permID }
        });
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 10 }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showDiviHandler() {
        let diviDisplay = {}
        if (this.state.diviDisplay.isTj) {
            diviDisplay = {
                div3:'',
                div2:'none',
                lable1:'返回',
                isTj:false,
            }
        } else {
            diviDisplay = {
                div3:'none',
                div2:'',
                lable1:'设置综合收益目标',
                isTj:true,
            }
        }
        let diviList = [];
        this.setState({diviDisplay,diviList})
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    addSeachXghmHandler() {
        if (this.state.diviList.length === 0) {
            message.error('设置综合目标失败！请选择一个主客户！');
            return;
        }
        let sdate =null;
        let edate = null;
        let cksd = 0;
        let ckrj=0;
        let lr=0;
        let zs=0;
        const witDividatas = this.state.diviList;
        if (witDividatas.length <= 0) {
            message.info('请选择要设置综合目标的主客户!');
            return;
        }
        let CUID = 0;
        CUID = Number(witDividatas[0].CUID);
        const form = this.refs.CompClieZhsrMbsdCxForm.getForm()
        let isok = true;
        form.validateFields((err, values) => {
            if (!err) {
                if (values.SDATE !== "" && values.SDATE !== undefined && values.SDATE !== null) {
                    sdate = values.SDATE
                }else {
                    message.error('目标开始日期不能为空！');
                    isok = false
                }
                if (values.EDATE !== "" && values.EDATE !== undefined && values.SDATE !== null) {
                    edate = values.EDATE
                }else{
                    message.error('目标截止日期不能为空！');
                    isok = false
                }
                if (values.CKSD !== "" && values.CKSD !== undefined) {
                    cksd = Number(values.CKSD)
                }else{
                    message.error('目标上浮水平目标值不能为空！');
                    isok = false
                }
                if (values.CKRJ !== "" && values.CKRJ !== undefined) {
                    ckrj = Number(values.CKRJ)
                }else{
                    message.error('目标综合利润目标值不能为空！');
                    isok = false
                }
                // if (values.MNLR !== "" && values.MNLR !== undefined) {
                //     lr = Number(values.MNLR)
                // }else{
                //     message.error('利润目标值不能为空！');
                //     isok = false
                // }
                // if (values.ZSSR !== "" && values.ZSSR !== undefined) {
                //     zs = Number(values.ZSSR)
                // }else{
                //     message.error('中收目标值不能为空！');
                //     isok = false
                // }
            }
        })
        let dataSource ={
            CUID:CUID,
            SDATE:sdate,
            EDATE:edate,
            CKSD:cksd,
            CKRJ:ckrj,
            MNLR:lr,
            ZSSR:zs
        } 
        if (!isok) {
            return;
        }
        accountService.CompClieZhsyMbsdIns({ CUID,dataSource }
        ).then(function (data) {
            console.log(data)
            if (data === "NO") {
                message.error('设置失败！主客户只能设置一个收益目标！');
                return;
            }  else if (data === "OK"){
                message.info('设置综合收益目标成功！');
                this.props.dispatch({
                    type: `${daoName}/fetch`,
                    payload: { daoName }
                });
                let diviDisplay = {
                    div3:'none',
                    div2:'',
                    lable1:'设置综合收益目标',
                    isTj:true,
                }
                let glhmDataSource = [];
                let diviList = [];
                this.setState({diviDisplay,glhmDataSource,diviList})
                this.props.dispatch({
                    type: `${daoName}/setSelectedRowKeys`,
                    payload: { selectedRowKeys: [] }
                });
            }
        }.bind(this));
    }
    submitSeachXghmHandler() {
        const datas = this.refs.diviUphmTable.state.datas;
        const witDividatas = this.state.diviList;
        if (witDividatas.length <= 0) {
            message.info('请选择要关联客户的主客户!');
            return;
        }
        let CUID = 0;
        CUID = Number(witDividatas[0].CUID);
        let dataSource = []
        datas.map(d => {
            let data = {
                CUID: CUID,
                LCUID: Number(d.CUID)
            }
            dataSource.push(data);
        })
        accountService.CompClieKhglInsGl({ CUID,dataSource }
        ).then(function (data) {
            if (data !== "OK") {
                message.info('设置综合收益目标失败！');
                return;
            } else if (data === "OK"){
                message.info('关联客户添加成功！');
                this.props.dispatch({
                    type: `${daoName}/fetch`,
                    payload: { daoName }
                });
            }
        }.bind(this));
        let diviDisplay = {
            div3:'none',
            div2:'',
            lable1:'设置综合收益目标',
            isTj:true,
        }
        let glhmDataSource = [];
        let diviList = [];
        this.setState({diviDisplay,glhmDataSource,diviList})
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    delSymb(){
        const otherkey = this.state.otherkey
        const keys = this.props.selectedRowKeys
        if (otherkey===-1){
            message.error("请选择要删除的收益目标数据行！")
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除该收益目标吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                accountService.delSymbzx({ otherkey }
                ).then(function (data) {
                    if (data === 'OK') {
                        message.success('删除收益目标成功')
                        this.props.dispatch({
                            type: `${daoName}/fetch`,
                            payload: { daoName }
                        });
                    } else{
                        message.error('删除失败！' + data)
                        return;
                    }
                }.bind(this)).catch(function (ex) {
                    console.log('请求出错', ex)
                });
                this.props.dispatch({
                    type: `${daoName}/setSelectedRowKeys`,
                    payload: { selectedRowKeys: [] }
                });
            }
        });
    }
    render() {
        let { showEdit, record, offsetHeight, permID, popedomTypes } = this.props
        let height = (offsetHeight - 128) * 0.50 - 41
        let data = []
        let pTypes = popedomTypes[permID]
        if (pTypes.indexOf("2") !== -1) {
            data.push({ value: '3', label: this.state.diviDisplay.lable1, onClick: this.showDiviHandler.bind(this) })
            data.push({ value: '4', label: "删除综合收益目标", onClick: this.delSymb.bind(this) })
        }
        const controlsFilter = [
            { name: 'CX', required: false, type: 'button-group', grid: 24 / 24, data: data },
          ];
        const controlsUphm = [
            { name: 'SDATE', required: false, type: 'date', label: '起始日', grid: 4 / 24, layout: { labelSpan: 8, wrapperSpan: 16 }, dataType: "date" },
            { name: 'EDATE', required: false, type: 'date', label: '截止日', grid: 4 / 24, layout: { labelSpan: 8, wrapperSpan: 16 }, dataType: "date"  },
            { name: 'CKSD', required: false, type: 'number', label: '目标上浮水平', grid: 4 / 24, layout: { labelSpan: 13, wrapperSpan: 11 }, dataType: 'number' },
            { name: 'CKRJ', required: false, type: 'number', label: '目标综合利润', grid: 4 / 24,  layout: { labelSpan: 13, wrapperSpan: 11 }, dataType: 'number' },
            // { name: 'MNLR', required: false, type: 'number', label: '利润(万)', grid: 3 / 24,  layout: { labelSpan: 12, wrapperSpan: 12 }, dataType: 'number' },
            // { name: 'ZSSR', required: false, type: 'number', label: '中收(万)', grid: 3 / 24, layout: { labelSpan: 12, wrapperSpan: 12}, dataType: 'number' },
            { name: 'button', required: false, type: 'button-group', grid: 1 / 24, data: [{ value: '1', label: '保存', onClick: this.addSeachXghmHandler.bind(this) }] },
        ]
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create} style={{ paddingBottom: '-16px' }}>
                    <EditFrom ref="CompClieZhsrmbCx" daoName={daoName} controls={controlsFilter} record={record} clearItemMargin={true} />
                    </div>
                    <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls}  onSelectChange={this.onSelectChangeHandler.bind(this)} height={height} permID={permID} />
                    <div style={{ display: this.state.diviDisplay.div2 }} id="showCompDiviDiv" >
                        <CompClieZhsrMbsdCxForm permID={permID} />
                    </div>
                    <div style={{ display: this.state.diviDisplay.div3 }} id="UpCompfkhm">
                        <DataEditTable columns={columnsUphmDivi} dataSource={this.state.glhmDataSource} ref="diviUphmTable"
                            height={150} keyName={"CUID"} footer={false} multiSelect={true} />
                        <EditFrom ref="CompClieZhsrMbsdCxForm" daoName={daoName} controls={controlsUphm} record={record} clearItemMargin={true} />
                    </div>
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, list, keyName } = state[daoName];
    const { offsetHeight, userID, orgID, pOrgID, popedomTypes } = state.menus
    const otherSelectedRowKeys = state['CompClieZhsyMbsd'].selectedRowKeys;
    return {
        userID,
        orgID,
        pOrgID,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        list,
        keyName,
        offsetHeight,
        record,
        otherSelectedRowKeys
    }
}
CompClieZhsrMbsdForm = connect(mapStateToProps)(CompClieZhsrMbsdForm)
export default CompClieZhsrMbsdForm;

let render = (props) => React.createElement(CompClieZhsrMbsdForm, props);
let f = new Factory()
f.set("CompClieZhsrMbsdForm", render)
